package com.jeff.cloud.consumermovie.controller;

import com.jeff.cloud.consumermovie.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 测试负载均衡：
 * 1、虚拟主机名与虚拟IP非常类似，可将其简单理解成为提供者的服务名称，默认情况下虚拟主机名和服务名称是一致的。
 * 当然也可以配置属性eureka.instance.virtual-host-name或者eureka.instance.secure-virtual-host-name指定虚拟主机名。
 * 2、不能将restTemplate.getForObject(...)与loadBalancerClient.choose(...)写在同一个方法中，两者会冲突，restTemplate实际上是一个Ribbon客户端，本身已经包含“choose”的行为
 * @author: jeff
 * @date: 2021/8/6 14:35
 */
@RestController
public class MovieController {
    private static final Logger LOGGER = LoggerFactory.getLogger(MovieController.class);

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /*
     *
     * 请求地址已更改为用户微服务的虚拟主机名，当Ribbon和Eureka配合使用时，会自动将虚拟主机名映身成微服务的网络地址。
     * @return:
     * @author: jeff
     * @date: 2021/8/9 10:13
     */
    @GetMapping("user/{id}")
    public User findById(@PathVariable Long id){
        return this.restTemplate.getForObject("http://microservice-provider-user/"+id,User.class);
    }
    @GetMapping("log-user-instance")
    public void logUserInstance(){
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user");
        //打印当前选择的是哪个节点
        MovieController.LOGGER.info("{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());
    }


    /*@GetMapping("/user/{id}")
    public User findById(@PathVariable Long id){
        return this.restTemplate.getForObject("http://localhost:8000/"+id,User.class);
    }

    @Value("${user.userServiceUrl}")
    private String userServiceUrl;
    @GetMapping("/user2/{id}")
    public User findById2(@PathVariable Long id){
        return this.restTemplate.getForObject(this.userServiceUrl+id,User.class);
    }*/
}
